<?php

namespace app\server\im\model;

use app\common\model\Config;
use JMessage\IM\Message;

/**
 * 开放数据操作
 * Class Index
 * OAuth2.0 ClientCredentials
 * @package app\im\controller
 */
class Messages
{

    /**
     * jmessage 相关参数
     * @var string
     */
    private $appKey = '';
    private $masterSecret = '';
    private $client;

    public function __construct()
    {
        $this->appKey = Config::get('im_config.appKey');
        $this->masterSecret = Config::get('im_config.masterSecret');
    }


    /**
     * jmessage 对象
     * @return \JMessage\JMessage
     */
    private function getClient()
    {
        if (!$this->client) {
            return new \JMessage\JMessage($this->appKey, $this->masterSecret);
        }
        return $this->client;

    }

    /**
     * 发送一对一消息通知
     * @param $target
     * @param $content
     * @return bool
     */
    private function sendSingleMessage($target, $content)
    {
        $message = new Message($this->getClient());
        $from = [
            'type' => 'admin',
            'id' => '10001'

        ];
        $target = [
            'type' => 'single',
            'id' => $target
        ];
        $msg = [
            'text' => $content['msg_content']['description'],
            'extras' => $content
        ];

        $r = $message->sendText("1", $from, $target, $msg);

        if (is_string($r)) {
            //记录错误记录
            //Log::error('im 消息发送超时 ' . $r);
            return false;
        }
        if ($r['http_code'] == 201) {
            return true;
        }
        //记录错误记录
        //Log::error('im 消息发送失败 ' . var_export($r, true));
        return false;

    }

    /**
     * 发送普通消息
     * @param string $target
     * @return bool
     */
    /*public function sendText($target = '', $text = '')
    {
        $message = new Message($this->getClient());
        $from = [
            'type' => 'admin',
            'id' => '10000'

        ];

        $target = [
            'type' => 'single',
            'id' => $target
        ];


        $msg = [
            'text' => $text,
        ];

        $r = $message->sendText("1", $from, $target, $msg);

        if (is_string($r)) {
            //记录错误记录
            Log::error('im 消息发送超时 ' . $r);
            return false;
        }
        if ($r['http_code'] == 201) {
            return true;
        }
        //记录错误记录
        Log::error('im 消息发送失败 ' . var_export($r, true));
        return false;
    }*/

    /**
     * 发送自定义通知
     * @return \think\response\Json
     */
    public function sendCustomNotice()
    {

        $body = file_get_contents("php://input");
        $body = json_decode($body, true);
        $user_id = intval($body['to_user']);
        if (empty($user_id)) {
            return Common::returnAjax('IM_PUSH_MESSAGE_FAILED', 'user_id 错误', 4008);
        }
        /**
         * {
         * "to_user":""123,
         * "thumb": "http://ww.bao.com/1.jpg",
         * "original_img": "http://ww.bao.com/2.jpg",
         * "title": "这是titil",
         * "description": "这是描述",
         * "createTime": "123456132",
         * "url": "http://www.baidu.com",
         * "buttons": [{
         * "title": "按钮标题",
         * "url": "http://www.baidu.com"
         * }, {
         * "title": "按钮标题",
         * "url": "http://www.baidu.com"
         * }]
         * }
         */
        if (!$body['buttons'] || !is_array($body['buttons'])) {
            return Common::returnAjax('IM_PUSH_MESSAGE_FAILED', '发送失败,内容体格式解析错误', 4008);
        }

        $buttons = [];

        foreach ($body['buttons'] as $k => $v) {
            if (empty($v['title']) || empty($v['url'])) {
                return Common::returnAjax('IM_PUSH_MESSAGE_FAILED', '发送失败,内容体格式解析错误', 4008);
            }
            $buttons[$k] = [];
            $buttons[$k]['title'] = htmlspecialchars($v['title'], ENT_QUOTES);
            $buttons[$k]['url'] = htmlspecialchars($v['url'], ENT_QUOTES);
        }

        /**
         * 自定义通知
         */
        $message_body = [
            'msg_type' => 'CUSTOM_NOTICE',
            'msg_content' => [
                //缩略图
                'thumb' => $body['thumb'],
                //原图
                'original_img' => $body['original_img'],
                //标题
                'title' => htmlspecialchars($body['title'], ENT_QUOTES),
                //描述
                'description' => htmlspecialchars($body['description'], ENT_QUOTES),
                //时间
                'createTime' => intval($body['createTime']),
                //详情地址 默认按钮动作
                'url' => htmlspecialchars($body['url'], ENT_QUOTES),
                'buttons' => $buttons
            ]
        ];

        //目标用户
        $target = 'user_' . $user_id;
        $r = $this->sendSingleMessage($target, $message_body);
        if ($r) {
            return Common::returnAjax('ok', 'success', 0);
        }
        return Common::returnAjax('IM_PUSH_MESSAGE_FAILED', '发送失败', 4008);

    }

}